from    SimpleXMLRPCServer  import SimpleXMLRPCServer
import  sys, traceback,os,string
import  win32api,win32process, winnt
from    re import findall as reFindall, compile as reCompile

Home_Dir    =   os.getcwd().replace(";","")+"\\"
ObjFile     =   Home_Dir + 'ConfigData.txt'

def ReadObj(myFile):
    try     :
        toFile  =   open(myFile,'r')
        Data    =   toFile.readlines()
        toFile.close()
        Obj     =   {}
        for LineData in Data    :
            if      'HOST=' in LineData  :
                Var =   'HOST'
                Exp =   reCompile('HOST=(\d+\.\d+.\d+.\d+)')
            elif    'PORT=' in LineData  :
                Var =   'PORT'
                Exp =   reCompile('PORT=(\d+)')
            elif    'PASS=' in LineData  :
                Var =   'PASS'
                Exp =   reCompile('PASS=(\w+)')
            elif    'APPS='  in LineData  :
                if not Obj.has_key('APPS')  :   Obj['APPS'] =   {}
                Var =   'APPS'
                Exp =   reCompile('APPS=(.+);(.+)')
            Results = reFindall(Exp,LineData)
            #print str(Results)
            if      len(Results) ==  1          :
                if  len(Results[0])  == 2       :
                    #print str(Results[0])
                    Obj['APPS'][str(Results[0][0])] = str(Results[0][1])
                else                            :
                    Obj[Var] =  str(Results[0])
            #print str(Obj)
        return Obj
    except  :
        traceback.print_exc()
        return None


## Read the Obj Data file if its not there or invalid use DataObj value 
ObjData = ReadObj(ObjFile)
#print ObjData

def GetProcessNames():
    id_list = win32process.EnumProcesses()
    result = ' '
    for id in id_list:
        try:
            try:
                proc_handle     =   win32api.OpenProcess(
                        winnt.PROCESS_QUERY_INFORMATION | winnt.PROCESS_VM_READ,
                        False, id)
                module_handle   =   win32process.EnumProcessModules(proc_handle)[0]
                process_path    =   win32process.GetModuleFileNameEx(proc_handle, module_handle)
                result          +=  str(os.path.basename(process_path))
            finally:
                ##traceback.print_exc()
                win32api.CloseHandle(proc_handle)
        except:
            ##traceback.print_exc()
            pass
    return result


def CheckProcess(ProcName):
    try     :
        print '--CheckProcess -- Started with :'+ str(ProcName)
        AllProcs    =   GetProcessNames()
        if  AllProcs  !=  None  :
            print str(AllProcs)
            if      str(ProcName) in AllProcs       :   Answer  =   True
            else                                    :   Answer  =   False
            print '--CheckProcess -- Finished '
            return  Answer
        return False
    except  :
        traceback.print_exc()
        return False


def CheckPassKey(PassKey)   :
    try     :
        if ObjData.has_key('PASS')  and ObjData['PASS'] == PassKey  :
            print '--PassKey Good--'
            return True
        else        :
            print '--PassKey Failed--'
            return False
    except  :
        traceback.print_exc()
        return False

        
class AllProcs:
    ## These functions can be seen from xmlrpc client

    ## Start the Selected Program / Application
    def StartProcess(self,PassKey,ProcName) :
        try     :
            print '--StartProcess -- '+ str(ProcName)            
            if  ( CheckPassKey(PassKey) )   :
                if not ProcName in ObjData['APPS'].keys()   :
                    print '** OBJECT NOT IN LIST **'
                    return 'Undefined',False
                else                                        :
                    if not ( CheckProcess(ProcName) )       :
                        print '--Process :'+ str(ProcName) +' -- Not Running...'
                        PathExec    =   ObjData['APPS'][str(ProcName)]
                        Dir         =   os.path.dirname(PathExec)
                        os.chdir(Dir)
                        Pid         =   os.spawnl(os.P_NOWAIT,PathExec)
                        os.chdir(Home_Dir)
                        if Pid >    0   :
                            return 'Started',True
                    else            :
                        return 'Running',True
            else        :
                return 'PassKey',False
            return 'Unknown',False
        except  :
            traceback.print_exc()
            return 'Error',False


    ## Give me a list of the Available programs I can start in a Text String
    def StartOptions(self,PassKey) :
        try     :
            print '-- StartOptions -- '
            if  ( CheckPassKey(PassKey) )   :
                Keys    =   ' '
                for k in ObjData['APPS'].keys() :
                    Keys    +=  str(k) +' '
                return Keys,True
            else        :
                return 'PassKey',False
        except  :
            traceback.print_exc()
            return 'Error',False


# Create server
server = SimpleXMLRPCServer((ObjData['HOST'],int(ObjData['PORT'])))
server.register_introspection_functions()
server.register_instance(AllProcs())
# Run the server's main loop
print 'Server Started on HOST:'+ str(ObjData['HOST']) +' -- PORT:'+ str(ObjData['PORT'])
server.serve_forever()
